package com.example.coolweather.util;

import android.text.TextUtils;

import com.example.coolweather.db.County;
import com.example.coolweather.db.Province;
import com.example.coolweather.db.City;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Utility {
    /**
     * 解析网络返回的JSON数据，并且存入对应的数据库表中
     * @param response
     * @return true 解析成功，并写入表中，否则失败
     * JSONArray JSONObject
     */

    public static boolean handleProvinceResponse(String response){//ctrl+alt+t
        try {
            JSONArray jsonArray = new JSONArray(response);
            for (int i =0;i <jsonArray.length();i++){
//解析数据，封装到Province对象中
                JSONObject o =jsonArray.getJSONObject(i);
                Province province=new Province();
                province.setProvinceName(o.getString("name"));
                province.setProvinceCode(o.getInt("id"));

                province.save();//存入数据库表
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }
    public static boolean handleCityResponse(String response,int provinceId){
        if (!TextUtils.isEmpty(response)){
            try {
                JSONArray allCities = new JSONArray(response);
                for (int i = 0;i< allCities.length();i++){
                    JSONObject cityObject = allCities.getJSONObject(i);
                    City city = new City();
                    city.setProvinceID(provinceId);
                    city.setCityCode(cityObject.getInt("id"));
                    city.setCityName(cityObject.getString("name"));
                    city.save();


                }
                return true;
            } catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return false;
    }


    public static boolean handleCountyResponse(String response,int cityId){
        if (!TextUtils.isEmpty(response)){
            try {
                JSONArray allCounties = new JSONArray(response);
                for (int i = 0;i < allCounties.length();i++){
                    JSONObject countyObject = allCounties.getJSONObject(i);
                    County county = new County();
                    county.setCountryName(countyObject.getString("name"));
                    county.setWeatherId(countyObject.getString("weather_id"));
                    county.setCityId(cityId);
                    county.save();


                }
                return true;
            } catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return false;
    }
}